<template>
    <section class="form-container">
        <el-form :inline="false" :model="filter" ref="filterRef"  size="mini"  class="form-filter" label-width="80px">
            <el-form-item label="搜索类型">
              <el-button-group>
                <el-button :type="searchType == SEARCH_TYPE_BY_DATE ? 'primary': ''" icon=""
                  @click="switchSearchType(SEARCH_TYPE_BY_DATE)">日期搜索</el-button>
                <el-button :type="searchType == SEARCH_TYPE_BY_PRECISE ? 'primary': ''"
                  @click="switchSearchType(SEARCH_TYPE_BY_PRECISE)">精确搜索</el-button>
              </el-button-group>
            </el-form-item>

            <div v-show="searchType == SEARCH_TYPE_BY_DATE">
                <el-form-item label="日期" prop="dateRange">
                    <div style="display:flex;">
                        <div>
                              <el-button-group>
                                <el-button :type="index == dateIndex ? 'primary': ''" v-for="(item,index) in todayOptions" :key="index"
                                  @click="selDate(index)" size="small">{{item.name}}</el-button>
                              </el-button-group>
                          </div>
                          <div style="margin-left:10px;">
                              <el-date-picker type="daterange" v-model="filter.dateRange" format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"
                                range-separator="至" clearable size="small" @change="selDateRange">
                              </el-date-picker>
                          </div>
                      </div>
                </el-form-item>

                <el-form-item label="线路" prop="lineIds">
                    <el-checkbox-group v-model="filter.lineIds">
                      <el-checkbox v-for="(item, index) in lineOptions" :key="index" :label="item.id">
                        {{item.lineName}}
                      </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="时间" prop="timeArr" style="display:inline-block;">
                      <el-select v-model="filter.timeArr" multiple clearable filterable>
                          <el-option
                              v-for="item in timeOptions"
                              :key="item"
                              :label="item"
                              :value="item"
                          />
                      </el-select>
                </el-form-item>

               <el-form-item label="司机" prop="driverId" style="display:inline-block;">
                   <el-select
                       v-model="filter.driverId"
                       filterable
                       clearable
                   >
                       <el-option
                           v-for="item in driverOptions"
                           :key="item.id"
                           :label="item.driverName"
                           :value="item.id"
                       />
                   </el-select>
               </el-form-item>

               <el-form-item label="车型" prop="vehicleTypeId" style="display:inline-block;">
                   <el-select
                       v-model="filter.vehicleTypeId"
                       filterable
                        clearable
                   >
                       <el-option
                           v-for="item in vehicleTypeOptions"
                           :key="item.id"
                           :label="item.vehicleTypeName"
                           :value="item.id"
                       />
                   </el-select>
               </el-form-item>

                <el-form-item label="班次状态" prop="status" style="display:inline-block;">
                  <el-select v-model="filter.status" clearable filterable>
                    <el-option v-for="item in Dict.enums.arrangeStatus" :key="item.code" :label="item.name"
                      :value="item.code" />
                  </el-select>
                </el-form-item>

            </div>
            <!-- 日期搜索 end -->

            <!-- 精确搜索 start -->
            <div v-show="searchType == SEARCH_TYPE_BY_PRECISE">
              <el-form-item label="班次编码" prop="arrangeCode" style="display:inline-block;">
                <el-input v-model="filter.arrangeCode" placeholder="请输入" clearable />
              </el-form-item>
              <el-form-item label="司机姓名" prop="driverName" style="display:inline-block;">
                <el-input v-model="filter.driverName" placeholder="请输入" clearable  />
              </el-form-item>
              <el-form-item label="司机电话" prop="driverPhone" style="display:inline-block;">
                <el-input v-model="filter.driverPhone" placeholder="请输入" clearable  />
              </el-form-item>
              <el-form-item label="车牌号" prop="licensePlateNumber" style="display:inline-block;">
                <el-input v-model="filter.licensePlateNumber" placeholder="请输入" clearable  />
              </el-form-item>
            </div>
            <!-- 精确搜索 end -->


            <el-form-item>
                <el-button type="primary" @click="getPage()" icon="el-icon-search">查询</el-button>
                <el-button @click="resetFilter()" icon="el-icon-refresh-left">重置</el-button>
                <el-button @click="showCreateArrange({})" icon="el-icon-plus">添加</el-button>
            </el-form-item>
        </el-form>
        <div class="form-content">
            <el-table
                v-loading="loading"
                style="width: 100%"
                :data="page.records"
                border
                stripe
                @expand-change="openArrangeSectionList"
                :header-cell-style = "headerCellStyle"
            >
                <el-table-column type="expand">
                    <template #default="props">
                        <div>
                            <el-table :data="sectionList[props.row.arrangeCode]" border style="">
                                <el-table-column prop="arrangeSectionCode" label="班次段编码" width="130"/>
                                <el-table-column prop="lineSectionName" label="班次段名称" width="160"/>
                                <el-table-column prop="startTimeFormat" label="发车时间"/>
                                <el-table-column label="起点">
                                    <template #default="scope">
                                        {{scope.row.startStationName}}【{{scope.row.startCarParkName}}】
                                    </template>
                                </el-table-column>
                                <el-table-column label="终点">
                                    <template #default="scope">
                                        {{scope.row.endStationName}}【{{scope.row.endCarParkName}}】
                                    </template>
                                </el-table-column>
                                <el-table-column prop="didSaleSeatNum" label="已售/占座/剩余/总数">
                                    <template #default="scope">
                                        <b :class="scope.row.didSaleSeatNum>0?'red':''">{{ scope.row.didSaleSeatNum }}</b> / {{ scope.row.lockSeatNum }} / {{ scope.row.surplusSeatNum }} / {{ scope.row.canSaleSeatNum }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="状态" width="80px">
                                    <template #default="scope">
                                        <el-tag v-if="scope.row.status" type="success">正常</el-tag>
                                        <el-tag v-else type="info">撤消</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column fixed="right" label="操作" width="239">
                                    <template #default="scope">
                                        <el-button size="mini" @click="toAddTicketOrder(scope.row.arrangeSectionCode)" type="text">添加车票订单</el-button>
                                        <el-button size="mini" @click="showSeat(scope.row)" type="text" >座位管理</el-button>
                                        <el-button size="mini"  @click="$router.push('/ticketOrder/index?arrangeSectionCode=' + scope.row.arrangeSectionCode)" type="text">班次段订单</el-button>

                                        <el-popconfirm title="确定撤消班次段吗？" v-if="scope.row.status==1" @onConfirm="arrangeSectionStatusSwitch(false,scope.row)" >
                                            <el-button slot="reference" size="mini" type="text" style="margin-right:10px;">撤消班次段</el-button>
                                        </el-popconfirm>

                                        <el-popconfirm title="确定恢复班次段吗？" v-if="scope.row.status==0" @onConfirm="arrangeSectionStatusSwitch(true,scope.row)" >
                                            <el-button slot="reference" size="mini" type="text" style="margin-right:10px;">恢复班次段</el-button>
                                        </el-popconfirm>
                                        <el-popconfirm title="确定删除吗？" @onConfirm="handleDeleteLineSection(scope.row)" >
                                            <el-button slot="reference" size="mini" type="text">删除</el-button>
                                        </el-popconfirm>

                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="arrangeCode" label="班次编码" width="130"/>
                <el-table-column prop="lineName" label="线路名称" width="160"/>
                <el-table-column prop="startTimeFormat" label="始发时间" width="130"/>

                <el-table-column prop="driverName" label="司机" width="70"/>
                <el-table-column prop="didSaleSeatNum" label="乘客数" width="100">
                    <template #default="scope">
                        <b :class="scope.row.didSaleSeatNum > 0 ?'red':''">{{ scope.row.didSaleSeatNum }}</b>
                    </template>
                </el-table-column>
                <el-table-column prop="canSaleSeatNum" label="车型座位数" width="100"/>
                <el-table-column prop="discountedActivitiesName" label="活动"/>
                <el-table-column prop="maxUseCreditNum" label="可用积分" width="80"/>
                <el-table-column prop="updateName" label="更新人" width="80"/>
                <el-table-column prop="updateTime" label="更新时间" width="160"/>
                <el-table-column label="状态" width="80px">
                    <template #default="scope">
                        <el-tag :type="scope.row.statusStyle">
                            {{ scope.row.statusName }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="240">
                    <template #default="scope">
                        <el-button  v-if="!scope.row.driverId" size="mini" type="text" @click="showAppointDriver(scope.row)" style="margin-right:10px;">指派司机</el-button>
                        <el-popconfirm v-else="scope.row.driverId" title="确定取消司机吗？" @onConfirm="cancelAppointDriver(scope.row.arrangeCode)">
                            <el-button slot="reference" size="mini" type="text" style="margin-right:10px;">取消司机</el-button>
                        </el-popconfirm>

                        <!-- <el-button size="mini" @click="showSeatBatch(scope.row)" type="text" style="margin:5px 10px 0 0;">座位管理</el-button> -->

                        <el-button size="mini" @click="$router.push('/ticketOrder/index?arrangeCode=' + scope.row.arrangeCode)" type="text" style="margin:5px 10px 0 0;">班次订单</el-button>
                        <router-link :to="{ name: 'IntercityArrangePassenger', query: { arrangeCode: scope.row.arrangeCode } }" target="_blank" style="color:#1890ff;">乘客信息</router-link>

                        <el-popconfirm title="确定撤消班次吗？" v-if="scope.row.status==1" @onConfirm="cancelArrange(scope.row.arrangeCode)">
                            <el-button slot="reference" size="mini" type="text" style="margin-right:10px;">撤消班次</el-button>
                        </el-popconfirm>

                        <el-popconfirm title="确定恢复班次吗？" v-if="scope.row.status==0" @onConfirm="recoverArrange(scope.row.arrangeCode)">
                            <el-button slot="reference" size="mini" type="text" style="margin-right:10px;">恢复班次</el-button>
                        </el-popconfirm>
                        <el-popconfirm title="确定删除吗？" @onConfirm="handleDelete(scope.row.arrangeCode)" >
                            <el-button slot="reference" size="mini" type="text">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                background
                :current-page="page.current"
                :page-sizes="[10, 20, 30, 50,100]"
                :page-size="page.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                style="margin-top:20px;"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
            <CreateArrange ref="createArrangeRef" @refresh="getPage()"/>
            <AppointDriver ref="appointDriverRef" @refresh="getPage()"/>
            <Seat ref="seatRef" @refresh="getArrangeSectionList"/>
            <SeatBatch ref="seatBatchRef" @refresh="getPage()"/>
        </div>
    </section>
</template>
<script>
import {ArrangeApi} from '@/api/intercity/ArrangeApi'
import {ArrangeSectionApi} from '@/api/intercity/ArrangeSectionApi'
import {DriverApi} from '@/api/user/DriverApi'
import {LineApi} from '@/api/intercity/LineApi'
import {VehicleTypeApi} from '@/api/user/VehicleTypeApi'
import {Common} from '@/utils/common'
import CreateArrange from './CreateArrange.vue'
import AppointDriver from './AppointDriver.vue'
import SeatBatch from './SeatBatch.vue'
import Seat from '../arrange-section/Seat.vue'

export default {
    name: 'ArrangeList',
    components: {
        CreateArrange,
        AppointDriver,
        Seat, SeatBatch
    },
    data() {
        return {
            page: {
                total: 0,
                size: 10,
                current: 1,
                pages: 0,
                records: []
            },
            filter: {
                dateRange:[],
                lineIds:[],
                timeArr:[],
                driverId:'',
                vehicleTypeId:'',
                status:'',

                arrangeCode:'',
                driverName:'',
                driverPhone:'',
                licensePlateNumber:''
            },
            loading: false,
            sectionList: {},
            createArrangeRef: null,
            headerCellStyle:{
                "background-color":"#F2F5FC"
            },

            // 搜索类型 1日期搜索，2精确搜索
            searchType: 1,
            // 日期搜索
            SEARCH_TYPE_BY_DATE: 1,
            // 精确搜索
            SEARCH_TYPE_BY_PRECISE: 2,

            // 日期列表
            todayOptions: [],
            dateIndex: '',

            lineOptions: [],
            timeOptions: [],
            driverOptions: [],
            vehicleTypeOptions: []

        }
    },
    created() {
        this.todayOptions = Common.todayOptions()
        this.timeOptions = Common.timeOptions()
        this.getLineList()
        this.getDriverOptions()
        this.getVehicleTypeOptions()
        this.selDate(2)

    },
    methods: {
        //************筛选start*************
        switchSearchType(type){
            this.searchType = type
            this.getPage()
        },
        selDate(index){
            this.dateIndex = index
            this.filter.dateRange = [this.todayOptions[index].date, this.todayOptions[index].date]
            this.getPage()
        },
        selDateRange(){
            this.dateIndex = -1
            this.getPage()
        },
        resetFilter() {
            if(this.searchType == this.SEARCH_TYPE_BY_DATE){
                this.filter.dateRange = []
                this.filter.lineIds = []
                this.filter.timeArr = []
                this.filter.driverId = ''
                this.filter.vehicleTypeId = ''
                this.filter.status = ''
                this.selDate(2)
            }else{
                this.filter.arrangeCode = ''
                this.filter.driverName = ''
                this.filter.driverPhone = ''
                this.filter.licensePlateNumber = ''
                this.page.records=[]
            }
        },
        //************筛选end*************

        // 获取线路列表
        getLineList() {
            LineApi.getList().then((data) => {
                this.lineOptions = data
            })
        },

        // 获取线路列表
        getDriverOptions() {
            DriverApi.getList({status:true}).then((data) => {
                this.driverOptions = data
            })
        },

        // 获取车型列表
        getVehicleTypeOptions() {
            VehicleTypeApi.getList([]).then((data) => {
                this.vehicleTypeOptions = data
            })
        },
        // 获取列表
        getPage() {
            this.sectionList = {}
            const params = {
                pageIndex: this.page.current,
                pageSize: this.page.size
            }
            if(this.searchType == this.SEARCH_TYPE_BY_DATE){
                params['dateRange']= [this.filter.dateRange[0]+'T00:00:00',this.filter.dateRange[1]+'T23:59:59']
                params['lineIds']= this.filter.lineIds
                params['timeArr']= this.filter.timeArr
                params['driverId']= this.filter.driverId
                params['vehicleTypeId']= this.filter.vehicleTypeId
                params['status']= this.filter.status
            }else{
                params['arrangeCode']= this.filter.arrangeCode
                params['driverName']= this.filter.driverName
                params['driverPhone']= this.filter.driverPhone
                params['licensePlateNumber']= this.filter.licensePlateNumber

                if(!this.filter.arrangeCode && !this.filter.driverName && !this.filter.driverPhone  && !this.filter.licensePlateNumber){
                    this.page.records=[]
                    return
                }
            }

            this.loading = true
            ArrangeApi.getPage(params).then((response) => {
                for (let i = 0; i < response.records.length; i++) {
                    response.records[i]['sectionList'] = []
                    response.records[i]['startTimeFormat'] = Common.timeFormat(response.records[i].startTime,4)
                }

                this.page = response
                this.loading = false
            }).catch((err) => {
                this.loading = false
            })
        },

        openArrangeSectionList(row, expanded) {
            if (this.sectionList[row.arrangeCode] === undefined) {
                this.getArrangeSectionList(row.arrangeCode)
            }
        },
        getArrangeSectionList(arrangeCode) {
            ArrangeSectionApi.getListByArrangeCode(arrangeCode).then((response) => {
                response.forEach(function(item){
                    item['startTimeFormat'] = Common.timeFormat(item.startTime,4)
                })
                this.$set(this.sectionList, arrangeCode, response)
            }).catch((err) => {
            })
        },

        handleDeleteLineSection(arrangeSectionItem){
            let that = this
            let newSectionList = that.sectionList[arrangeSectionItem.arrangeCode].filter(item => item.arrangeSectionCode != arrangeSectionItem.arrangeSectionCode)
            ArrangeSectionApi.delete(arrangeSectionItem.arrangeSectionCode).then((response) => {
                that.$set(this.sectionList, arrangeSectionItem.arrangeCode, newSectionList)
            })
        },

        // 取消班次
        cancelArrange(arrangeCode) {
            ArrangeApi.cancelArrange(arrangeCode).then((response) => {
                this.getPage()
                this.sectionList = {}
            })
        },

        // 恢复班次
        recoverArrange(arrangeCode) {
            ArrangeApi.recoverArrange(arrangeCode).then((response) => {
                this.getPage()
                this.sectionList = {}
            })
        },

        // 修改状态
        arrangeSectionStatusSwitch(val, item) {
            let that = this
            const params = {
                arrangeSectionCode: item.arrangeSectionCode,
                status: val
            }

            let newSectionList =Common.deepClone(that.sectionList[item.arrangeCode])
            newSectionList.forEach(function(o){
                if(o.arrangeSectionCode == item.arrangeSectionCode){
                    o.status = val
                }
            })

            ArrangeSectionApi.updateStatus(params).then((response) => {
                that.$set(this.sectionList, item.arrangeCode, newSectionList)
            })
        },

        // 删除数据
        handleDelete(id) {
            ArrangeApi.delete(id).then((response) => {
                this.getPage()
            })
        },

        handleSizeChange(val) {
            this.page.size = val
            this.page.current = 1
            this.getPage()
        },

        handleCurrentChange(val) {
            this.page.current = val
            this.getPage()
        },

        showCreateArrange(data) {
            this.$refs['createArrangeRef'].showCreateArrange(data)
        },

        showAppointDriver(item) {
            this.$refs['appointDriverRef'].show(item)
        },
        cancelAppointDriver(arrangeCode){
            ArrangeApi.cancelAppointDriver(arrangeCode).then((response) => {
                this.getPage()
            })
        },

        showSeat(data) {
            this.$refs['seatRef'].show(data)
        },
        showSeatBatch(data) {
            this.$refs['seatBatchRef'].show(data)
        },
        toAddTicketOrder(arrangeSectionCode){
            this.$router.push({
                name: 'TicketOrderCreate',
                query: {arrangeSectionCode}
            })
        }
    }
}

</script>

<style lang="scss" scoped>
    ::v-deep .el-table__expanded-cell{ padding-left: 48px; padding-right:0px;}
    .red{font-weight:bold; color:#900;}


</style>
